package com.cqeec.waimai.filter;

import com.alibaba.fastjson.JSON;
import com.cqeec.waimai.common.BaseContext;
import com.cqeec.waimai.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
//        直接可以运行的地址
        String[] urls = new String[]{
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
//        对上述请求地址放行
        boolean flag = CHECKURLS(uri,urls);
        if(flag){
            filterChain.doFilter(request,response);
            return;
        }
        String agent = request.getHeader("Agent");
//        判断是否是服务端发出的请求
        if(agent.equals("backend")){
//            判断session中是否有值
            if(request.getSession().getAttribute("employee")!=null){
                BaseContext.setThreadLocal((Long) request.getSession().getAttribute("employee"));
                filterChain.doFilter(request,response);
                return;
            }
        }
//        判断是否是服务端发出的请求
        if(agent.equals("front")){
//            判断session中是否有值
            if(request.getSession().getAttribute("user")!=null){
                BaseContext.setThreadLocal((Long) request.getSession().getAttribute("user"));
                filterChain.doFilter(request,response);
                return;
            }
        }
//        响应request.js
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    private boolean CHECKURLS(String uri, String[] urls) {
        for (String u : urls) {
            boolean match = antPathMatcher.match(u, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
